package com.yiba.vpn.controller;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.yiba.vpn.authorization.manager.TokenManager;
import com.yiba.vpn.authorization.model.TokenModel;
import com.yiba.vpn.config.ResultStatus;
import com.yiba.vpn.domain.User;
import com.yiba.vpn.dto.RefreshTokenDto;
import com.yiba.vpn.model.ResultModel;
import com.yiba.vpn.repository.UserRepository;
import com.yiba.vpn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 获取和删除token的请求地址，在Restful设计中其实就对应着登录和退出登录的资源映射
 *
 * @author ScienJus
 * @date 2015/7/30.
 */
@Api(value = "WfeeTokenAPI")
@RestController
@RequestMapping("/tokens")
public class TokenController {


    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private UserRepository userRepository;


    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.POST)
    @ApiOperation(value = "刷新获取token")
    public ResponseEntity<ResultModel> refreshToken(@RequestBody RefreshTokenDto refreshTokenDto) {
        if (null == refreshTokenDto || StringUtils.isEmpty(refreshTokenDto.getAccount()) || StringUtils.isEmpty(refreshTokenDto.getUuid())) {
            return new ResponseEntity<>(ResultModel.error(ResultStatus.REQUEST_PARAMS_ERROR), HttpStatus.OK);
        }
        User user = this.userRepository.findByAccount(refreshTokenDto.getAccount());
        if (null == user) {
            return new ResponseEntity<>(ResultModel.error(ResultStatus.USER_NOT_FOUND), HttpStatus.OK);
        }
        //生成一个token，保存用户登录状
        TokenModel tokenModel = userService.refreshToken(refreshTokenDto);
        return new ResponseEntity<>(ResultModel.ok(tokenModel), HttpStatus.OK);
    }


    @RequestMapping(value="refreshToken",method = RequestMethod.GET)
    public ResponseEntity<ResultModel> oauthRefreshToken(@RequestParam(value="refreshToken",required = false)String refreshToken) {
        if ( StringUtils.isEmpty(refreshToken)) {
            return new ResponseEntity<>(ResultModel.error(ResultStatus.REQUEST_PARAMS_ERROR), HttpStatus.OK);
        }
        return userService.oauthRefreshToken(refreshToken);
    }
}
